import { _decorator, CircleCollider2D, Collider2D, Color, Component, Contact2DType, MotionStreak, Node, RigidBody2D, SpriteFrame, Texture2D, v2, Vec2, Vec3 } from 'cc';
import { Drawlayer, UICtrl } from '../Ctrl/UICtrl';
import { Global, UnitType } from '../Util/Global';
import { EconomicCom } from './Component/EconomicCom';
import { Unit } from './Unit';
import { DestructableCom, IDestruction } from './Component/DestructableCom';
const { ccclass, property } = _decorator;

@ccclass('Bullet')
export class Bullet extends Unit implements IDestruction {

    @property
    public canLifeTime: number = 3;
    @property
    public atk: number = 1;

    protected target: Unit = null;

    protected trigger: CircleCollider2D = null;

    protected trail: Node = null;

    public _atk: number = 1;
    start(): void {
        super.start();

        this.unitType = UnitType.Bullet;

        for (let co of this.colliders) {
            if (co.tag == 1) {
                this.trigger = co as CircleCollider2D;
                this.trigger.radius = this.alertFieldRadius;

                //监听传感器碰撞事件 二者的rigibody和collider二者任意一个的group符合碰撞就会触发碰撞事件
                this.trigger.on(Contact2DType.BEGIN_CONTACT, this.onTriggerEnter, this);

                break;
            }
        }

        this.forward.set(1, 0);
        this.trail = this.node.getChildByName('trail');
        this._atk = this.atk;
    }

    protected onDisable(): void {
        super.onDisable();
        this._atk = this.atk;
        this.target = null;
        this.moveVec.set(0, 0);
        this.parentUnit = null;
    }

    _updateLogic(dt: number) {
        super._updateLogic(dt);

        if (this.trail) {
            this.trail.active = this.isInScreenPos;
        }
        this.updateLogic(dt);
    }

    /**替代update，不会影响下基类的update逻辑 */
    protected updateLogic(dt: number): void {
        if (this._lifeTime >= this.canLifeTime) {

            this.DestroySelf();
        }
        //这里不能用death了, 由于destructable可能被锁定那一刻就死了
        // else if (this.target && !this.target.death) { 
        else if (this.target && this.target.isValid && this.target.node.active) {

            this.AutoMove();
        }
        else {
            this.target = null;

            let angle = this.rigBody.linearVelocity.signAngle(this.forward) * 180 / Math.PI;
            this.node.setRotationFromEuler(0, 0, -angle);
            //勇往直前
            this.moveVec = this.forward.clone();
            this.GetRotatedPos(this.moveVec);//变成当前的正前方

            let newSpeedVec = this.rigBody.linearVelocity.add(this.moveVec);

            this.rigBody.linearVelocity = newSpeedVec;
        }

    }

    protected rendererUpdate_Gravity_Velocity(dt: number): void {
        if (Global.LinearVelocityRenderer && this.speedS > 10) {
            // let endPos = this._moveVec.clone().multiplyScalar(this.speedS / 5); // 终点坐标
            let endPos = this.rigBody.linearVelocity.clone().normalize().multiplyScalar(this.speedS / 5); // 终点坐标
            UICtrl.LineRenderer(this.unitWorldPos, this.unitWorldPos.add(this.ToVec3(endPos)), Color.RED, Drawlayer.View);
        }

        if (Global.GravityCricleRenderer) {
            UICtrl.CircleRenderer(this.unitWorldPos, this.alertFieldRadius / Global.CameraOrthoScale, Color.BLUE);
        }
    }

    /**设置目标 */
    SetTarget(target: Unit) {
        this.target = target;
        if (!this.IsEnemy(target)) {
            console.log('警告==>目标是自己人！！？');
        }
        else {
            let destructable = target.getComponent(DestructableCom);
            if (destructable) {
                destructable.AddLateDestruction(this);
            }
        }
    }

    GetDestructionValue() {
        return this._atk;
    }

    DestroySelf(reason?: string | number) {
        if (this.target && !this.target.death) {
            let destructable = this.target.getComponent(DestructableCom);
            if (destructable) {
                destructable.RemoveLateDestruction(this);
            }
        }

        super.DestroySelf(reason);
        // SoundCtrl.playEffect(null, "boom");
    }

    IsEnemy(unit: Unit): boolean {
        if (unit.unitType == UnitType.UnitPlanet) {

        }
        else if (!unit || !unit.node.active ||
            !(unit.unitType > UnitType.Bullet && unit.unitType <= UnitType.UnitSpacecra)) {
            return false;
        }
        if (unit.unitType == UnitType.UnitPlanet) {
            if (unit.getComponent(EconomicCom) == null) {
                return false;
            }
            else if (unit != this.parentUnit) {
                return true;
            }
        }
        if (unit
            && unit.parentUnit != this.parentUnit
            && unit != this.parentUnit) {
            return true;
        }
        return false;
    }

    protected onTriggerEnter(selfCollider: Collider2D, otherCollider: Collider2D) {
        super.onTriggerEnter(selfCollider, otherCollider);
        // 只在两个碰撞体开始接触时被调用一次

        let other = otherCollider.node.getComponent(Unit);
        if (!this.death && this.IsEnemy(other)) {
            let destructable = other.getComponent(DestructableCom);
            if (destructable) {
                destructable.OnDamage(this);
            }

            this.DestroySelf();
        }
        else if (other == this.target) {
            console.log('警告==>击中目标！但是是友方？！！');
        }
    }

    /**移动方向 */
    moveVec = new Vec2();

    protected _targetWorldPos = new Vec3();
    AutoMove() {

        this.target.node.getWorldPosition(this._targetWorldPos);

        // 计算物体需要移动的距离和方向
        let moveDir = this._targetWorldPos.subtract(this.unitWorldPos).normalize();//向量减法会改变自身

        this.moveVec.x = moveDir.x;
        this.moveVec.y = moveDir.y;

        this.moveVec.multiplyScalar(1 + this.moveAcceleration);
        let newSpeedVec = this.rigBody.linearVelocity.add(this.moveVec);

        this.rigBody.linearVelocity = newSpeedVec;
    }
}


